<template>
  <el-dialog :title="title" v-model="open" width="800px" append-to-body>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <!-- 基本信息 -->
      <!--     <el-form-item label="图号" prop="drawingNo">
        <el-input v-model="form.drawingNo" placeholder="请输入图号" readonly />
      </el-form-item> -->

      <!--       <el-form-item label="分类" prop="category">
        <el-input v-model="form.category" placeholder="请输入分类" readonly />
      </el-form-item> -->

      <!-- 保养类型设置 -->
      <el-form-item label="保养类型" prop="upkeepCategoryId" required>
        <el-select v-model="form.upkeepCategoryId" placeholder="请选择保养类型" class="!w-240px" @change="handleCategoryChange"
          filterable clearable>
          <el-option v-for="item in upkeepCategoryOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="核算方式" prop="accountMethod">
        <el-select v-model="form.accountMethod" placeholder="请选择核算方式" clearable class="!w-240px" disabled>
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_UPKEEP_CATEGORY_ACCOUNT_METHOD)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="保养周期(天)" prop="upkeepPeriod" required>
        <el-input-number v-model="form.upkeepPeriod" :min="0" :max="365" disabled />
      </el-form-item>

      <el-form-item label="制单周期(天)" prop="tobePeriod" required>
        <el-input-number v-model="form.tobePeriod" :min="0" :max="365" disabled />
      </el-form-item>

      <el-form-item label="提醒周期(天)" prop="reminderPeriod" required>
        <el-input-number v-model="form.reminderPeriod" :min="0" :max="30" disabled />
      </el-form-item>

      <!-- 保养项目 -->
      <el-form-item label="保养项目">
        <el-table :data="form.upkeepItems" stripe border>
          <el-table-column label="编号" prop="code" width="100" />
          <el-table-column label="名称" prop="name" />
          <!--      <el-table-column label="描述" prop="description" /> -->
          <el-table-column label="描述" align="center" prop="description">
            <template #default="scope">
              {{ stripHtml(scope.row.description) }}
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { UpkeepSetApi } from '@/api/mold/upkeepset'
import { UpkeepCategoryApi } from '@/api/mold/upkeepcategory'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'

const { t } = useI18n()

// 定义事件
const emit = defineEmits(['success'])

const open = ref(false)
const title = ref('')
const formRef = ref()
const moldId = ref()
const upkeepCategoryOptions = ref([])

const form = reactive({
  drawingNo: '',
  category: '',
  upkeepCategoryId: null,
  accountMethod: undefined,
  upkeepPeriod: 0,
  tobePeriod: 0,
  reminderPeriod: 0,
  upkeepItems: []
})

const rules = {
  upkeepCategoryId: [{ required: true, message: '保养类型不能为空', trigger: 'change' }],
  upkeepPeriod: [{ required: true, message: '保养周期不能为空', trigger: 'blur' }],
  reminderPeriod: [{ required: true, message: '提醒周期不能为空', trigger: 'blur' }]
}

/** 打开弹窗 */
const openForm = async (id: number, catId: number, drawingNo: string, category: string) => {
  moldId.value = id
  open.value = true
  title.value = '保养设置'

  // 设置图号和分类
  form.drawingNo = drawingNo || ''
  form.category = category || ''

  // 重置表单
  reset()

  // 加载保养类型选项
  await loadUpkeepCategories()

  // 如果有保养类型ID，加载数据
  if (catId) {
    try {
      form.upkeepCategoryId = catId

      const data = await UpkeepSetApi.getSetCat(catId)

      // 填充表单字段
      if (data.categoryDetail) {
        form.accountMethod = data.categoryDetail.accountMethod
        form.upkeepPeriod = data.categoryDetail.upkeepPeriod
        form.tobePeriod = data.categoryDetail.tobePeriod
        form.reminderPeriod = data.categoryDetail.reminderPeriod
      }

      // 填充保养项目
      form.upkeepItems = data.itemDetails || []
    } catch (error) {
      ElMessage.error('加载保养设置失败')
      console.error(error)
    }
  }
}

/** 加载保养类型选项 */
const loadUpkeepCategories = async () => {
  try {
    const data = await UpkeepCategoryApi.getUpkeepCategoryAll()

    if (data && Array.isArray(data)) {
      upkeepCategoryOptions.value = data.map(item => ({
        value: item.id,
        label: `${item.name} (${item.code})`
      }))
    } else {
      console.error('保养类型数据格式不正确:', data)
      ElMessage.error('加载保养类型失败: 数据格式不正确')
    }
  } catch (error) {
    console.error('加载保养类型失败:', error)
    ElMessage.error('加载保养类型失败')
  }
}

/** 保养类型变化 */
const handleCategoryChange = async (categoryId) => {
  try {
    if (!categoryId) return;

    const data = await UpkeepSetApi.getSetCat(categoryId)

    // 填充表单字段
    if (data.categoryDetail) {
      form.accountMethod = data.categoryDetail.accountMethod
      form.upkeepPeriod = data.categoryDetail.upkeepPeriod
      form.tobePeriod = data.categoryDetail.tobePeriod
      form.reminderPeriod = data.categoryDetail.reminderPeriod
    }

    // 填充保养项目
    form.upkeepItems = data.itemDetails || []
  } catch (error) {
    ElMessage.error('加载保养类型详情失败')
    console.error(error)
  }
}

/** 提交表单 */
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await UpkeepSetApi.updateCat(moldId.value, form.upkeepCategoryId)
        ElMessage.success('保存成功')
        // 触发成功事件
        emit('success')
        open.value = false
      } catch (error) {
        ElMessage.error('保存失败')
        console.error(error)
      }
    }
  })
}

/** 取消 */
const cancel = () => {
  open.value = false
  reset()
}

/** 重置表单 */
const reset = () => {
  form.upkeepCategoryId = null
  form.accountMethod = undefined
  form.upkeepPeriod = 0
  form.tobePeriod = 0
  form.reminderPeriod = 0
  form.upkeepItems = []
}

defineExpose({
  open: openForm
})


function stripHtml(html: string): string {
  if (!html) return ''
  const tmp = document.createElement('div')
  tmp.innerHTML = html
  return tmp.textContent || tmp.innerText || ''
}
</script>